package com.ogawa.chair7808.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.jeremyliao.liveeventbus.LiveEventBus;
import com.ogawa.base.Constant.CommmandNum;
import com.ogawa.base.utils.CommonUtil;
import com.ogawa.base.utils.StringUtils;
import com.ogawa.chair7808.R;
import com.ogawa.chair7808.bean.Device7808StateBean;
import com.ogawa.chair7808.manager.DataManager;
import com.ogawa.chair7808.manager.TimeBean;
import com.ogawa.chair7808.view.LongClickImageView2;
import com.ogawa.chair7808.view.MoveLayout;
import com.ogawa.chair7808.widget.LayoutGears5_7506;
import com.ogawa.chair7808.widget.LayoutGears6_7506;
import com.example.reslib.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.ogawa.base.Constant.Constant.LIVE_EVENT_BUS_KEY_UPDATE_TIME;
import static com.ogawa.base.Constant.MqttConstant.LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE;
import static com.ogawa.base.utils.StringUtils.numberToTime;


/**
 * 按摩手法
 * Created by LCH on 2018/1/29.
 */
public class MassageTechniqueFragment extends BaseTimeTaskFragment implements LongClickImageView2.onDownAction
        , View.OnClickListener, MoveLayout.OnChooseAction
//        ,IFraMassageView7506
{


    private View inflate;

    private RelativeLayout mLl3D;
    private RelativeLayout mLlDynamics;//力度
    private RelativeLayout mLlSpeed;
    private LinearLayout mLlSelectSkill;//选择手法
    private TextView tvTime;

    private TextView mTvFix;//定点，区间 全身
    private int flag_area = 0;//0 mTvFix 关闭（默认定点），1 定点开 2 区间 3 全身
    private int[] mRnImage = {R.drawable.hand_knead_normal_selector, R.drawable.hand_knead1_selector, R.drawable.hand_knead2_selector};//揉捏
    private int[] mQJImage = {R.drawable.hand_tap0_selector, R.drawable.hand_tap1_selector, R.drawable.hand_tap2_selector};//敲击
    private int[] mTNImage = {R.drawable.hand_roll_normal_selector, R.drawable.hand_roll_selected_selector};//推拿

    private int[] mPDImage = {R.drawable.hand_paida0_selector, R.drawable.hand_paida1_selector, R.drawable.hand_paida2_selector};//拍打
    private int[] mZYImage = {R.drawable.hand_zhiya0_selector, R.drawable.hand_zhiya1_selector, R.drawable.hand_zhiya2_selector};//指压
    private int[] mRDSImage = {R.drawable.hand_rds0_selector, R.drawable.hand_rds1_selector, R.drawable.hand_rds2_selector};//瑞典式

    private List<int[]> mImages = new ArrayList<>();


    private ImageView mHeadup;//up
    private ImageView mHeadDown;//DOWN
    private ImageView mIvWidthNoClick;//

    private FrameLayout mFlwidth;//宽度背景
    private ImageView mIvLeft, mIvRight;//宽度加减
    private ImageView mIvRN;//揉捏
    private ImageView mIvQJ;//敲击
    private ImageView mIvPD;//拍打
    private ImageView mIvRDS;//瑞典式
    private ImageView mIvZY;//指压
    private ImageView mIvTN;//推拿
    private List<ImageView> mIvSkills = new ArrayList<>();
    private String[] name = {"手法", "3D", "力度", "速度"};


    private LayoutGears6_7506 mLayout3D;
    private LayoutGears5_7506 mLayoutPower;
    private LayoutGears5_7506 mLayoutSpeed;
    private MoveLayout mLayout;
    private ScrollView mScroll;
    //机芯调节
    private boolean isClickUpOrDown = false;
    private long mClickUpDownTime = 0;
    private String mActionUpDown = "";//按上up   按下dowm
    private Disposable mDisposable;
    //宽度调节
    private boolean isClickWidth = false;
    private long mClickWidthTime = 0;
    private String mActionWidth = "";//按左left   按右right
    private Disposable mDisposableWidth;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        inflate = inflater.inflate(R.layout.fragment_massage_technique_7808, container, false);
        initView();
        LiveEventBus.get(LIVE_EVENT_BUS_KEY_UPDATE_TIME, TimeBean.class).observe(this, new androidx.lifecycle.Observer<TimeBean>() {
            @Override
            public void onChanged(TimeBean timeBean) {
                long min = timeBean.getMin();
                long second = timeBean.getSecond();
                setTextView(tvTime, "" + numberToTime(min) + " : " + numberToTime(second));
            }
        });

        LiveEventBus.get(LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE).observe(this, new androidx.lifecycle.Observer<Object>() {
            @Override
            public void onChanged(Object integer) {
                updateView();

            }
        });
        return inflate;
    }


    private void initView() {

        mHeadup = inflate.findViewById(R.id.headup);
        mHeadDown = inflate.findViewById(R.id.headdown);
        mScroll = inflate.findViewById(R.id.massage_fragment_scroll);
        mLayout = inflate.findViewById(R.id.massege_fragment_move_layout);
        mIvWidthNoClick = inflate.findViewById(R.id.iv_width_noclick);
        mLayout.setData(name);
        mLayout.setScollView(mScroll);
        mLayout.setAction(this);

        mHeadup.setOnClickListener(this);

        mHeadDown.setOnClickListener(this);

        mIvLeft = inflate.findViewById(R.id.iv_width_left);


        mIvRight = inflate.findViewById(R.id.iv_width_right);
        mIvLeft.setOnClickListener(this);
        mIvRight.setOnClickListener(this);
        mFlwidth = inflate.findViewById(R.id.fragment_mt_fl_width);
        tvTime = inflate.findViewById(R.id.tvTime);


        mIvRN = inflate.findViewById(R.id.fragment_mt_tv_knead);
        mIvQJ = inflate.findViewById(R.id.fragment_mt_tv_tap);
        mIvPD = inflate.findViewById(R.id.fragment_mt_tv_paida);
        mIvRDS = inflate.findViewById(R.id.fragment_mt_tv_swedish);
        mIvZY = inflate.findViewById(R.id.fragment_mt_tv_shiatsu);
        mIvTN = inflate.findViewById(R.id.fragment_mt_tv_roll);
        mImages.clear();
        mIvSkills.clear();
        mImages.add(mRnImage);
        mImages.add(mQJImage);

        mImages.add(mTNImage);
        mImages.add(mZYImage);
        mImages.add(mPDImage);
        mImages.add(mRDSImage);

        mIvSkills.add(mIvRN);
        mIvSkills.add(mIvQJ);
        mIvSkills.add(mIvTN);
        mIvSkills.add(mIvZY);
        mIvSkills.add(mIvPD);
        mIvSkills.add(mIvRDS);


        mLayout3D = inflate.findViewById(R.id.layout_3d);
        mLayoutPower = inflate.findViewById(R.id.linear_air_massage_strong);
        mLayoutSpeed = inflate.findViewById(R.id.linear_air_massage_speed);
        mLayout3D.setType(1);
        mLayoutPower.setType(1);
        mLayoutSpeed.setType(2);

        mTvFix = inflate.findViewById(R.id.fragmentFixpoint);
        mTvFix.setOnClickListener(this);
        mLl3D = inflate.findViewById(R.id.layout_3d);
        mLlDynamics = inflate.findViewById(R.id.linear_air_massage_strong);
        mLlSpeed = inflate.findViewById(R.id.linear_air_massage_speed);
        mLlSelectSkill = inflate.findViewById(R.id.linear_methods_to_select);

        mIvLeft.setOnClickListener(this);
        mIvRight.setOnClickListener(this);

        mIvRN.setOnClickListener(this);
        mIvQJ.setOnClickListener(this);
        mIvPD.setOnClickListener(this);
        mIvRDS.setOnClickListener(this);
        mIvZY.setOnClickListener(this);
        mIvTN.setOnClickListener(this);
        tvTime.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        int mWidth = StringUtils.getValue(DataManager.getInst().getDevice7808StateBean().getXPos());
        int mPoint = StringUtils.getValue(DataManager.getInst().getDevice7808StateBean().getYPos());
        int i = v.getId();
        if (i == R.id.tvTime) {
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                showDialog();

            }


        } else if (i == R.id.headup) {
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                if (mPoint < 10) {
                    mActionUpDown = "up";
                    setUpOrDown();
                    DataManager.getInst().sendCommond(CommmandNum.JIXINUP, "1");
                } else {
                    ToastUtils.showShortToast(getContext(), "机芯已在最高处");
                }

            }

        } else if (i == R.id.headdown) {
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                if (mPoint > 0) {
                    mActionUpDown = "down";
                    setUpOrDown();
                    DataManager.getInst().sendCommond(CommmandNum.JIXINDOWM, "2");
                } else {
                    ToastUtils.showShortToast(getContext(), "机芯已在最低处");
                }

            }


        } else if (i == R.id.fragmentFixpoint) {
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                DataManager.getInst().sendCommond(CommmandNum.DINGDQUJ, "3");

            }


        } else if (i == R.id.iv_width_left) {
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                if (mWidth > 0) {
                    mActionWidth = "left";
                    setWidthClick();
                    DataManager.getInst().sendCommond(CommmandNum.KUANDUSUB, "1");
                } else {
                    ToastUtils.showShortToast(getContext(), "宽度已最小");
                }


            }

        } else if (i == R.id.iv_width_right) {
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                if (mWidth < 3) {
                    mActionWidth = "right";
                    setWidthClick();
                    DataManager.getInst().sendCommond(CommmandNum.KUANDUADD, "2");
                } else {
                    ToastUtils.showShortToast(getContext(), "宽度已最大");
                }
            }

        } else if (i == R.id.fragment_mt_tv_knead) {//揉捏
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                DataManager.getInst().sendCommond(CommmandNum.ROUN, "3");
            }

        } else if (i == R.id.fragment_mt_tv_tap) {//敲击
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                DataManager.getInst().sendCommond(CommmandNum.QIAOJ, "3");
            }

        } else if (i == R.id.fragment_mt_tv_roll) {//推拿
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                DataManager.getInst().sendCommond(CommmandNum.TUINA, "3");
            }


        } else if (i == R.id.fragment_mt_tv_paida) {//拍打
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                DataManager.getInst().sendCommond(CommmandNum.PAIDA, "3");
            }

        } else if (i == R.id.fragment_mt_tv_shiatsu) {//指压
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                DataManager.getInst().sendCommond(CommmandNum.ZHIYA, "3");
            }

        } else if (i == R.id.fragment_mt_tv_swedish) {//瑞典
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                DataManager.getInst().sendCommond(CommmandNum.RUID, "3");
            }

        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void setWidth(int position) {
        if (position == 0) {
            mFlwidth.setBackgroundResource(R.mipmap.width0);
        } else if (position == 1) {
            mFlwidth.setBackgroundResource(R.mipmap.width1);
        } else if (position == 2) {
            mFlwidth.setBackgroundResource(R.mipmap.width2);
        } else if (position == 3) {
            mFlwidth.setBackgroundResource(R.mipmap.width3);
        } else {
            mFlwidth.setBackgroundResource(R.mipmap.width0);
        }

    }


    private void setArea(int position) {
        if (position == 0) {
            mTvFix.setSelected(false);
            mTvFix.setText("定点");
        } else if (position == 1) {
            mTvFix.setSelected(true);
            mTvFix.setText("定点");
        } else if (position == 2) {
            mTvFix.setSelected(true);
            mTvFix.setText("区间");
        }

    }


    /**
     * @param position 0揉捏，1敲击，2推拿，3敲揉，4指压，5瑞典；
     * @param stronger 强度
     */
    private synchronized void setSkill(int position, int stronger) {
        mIvSkills.get(position).setImageResource(mImages.get(position)[stronger]);
    }

    @Override
    public void onChoose(int position) {
        mLayout.setTectColor(position);
        switch (position) {
            case 0:
                mLlSelectSkill.setVisibility(View.VISIBLE);
                mLl3D.setVisibility(View.GONE);
                mLlSpeed.setVisibility(View.GONE);
                mLlDynamics.setVisibility(View.GONE);
                break;
            case 1:
                mLlSelectSkill.setVisibility(View.GONE);
                mLl3D.setVisibility(View.VISIBLE);
                mLlDynamics.setVisibility(View.GONE);

                mLlSpeed.setVisibility(View.GONE);
                break;
            case 2:
                mLlSelectSkill.setVisibility(View.GONE);
                mLl3D.setVisibility(View.GONE);
                mLlDynamics.setVisibility(View.VISIBLE);
                mLlSpeed.setVisibility(View.GONE);

                break;
            case 3:
                mLlSelectSkill.setVisibility(View.GONE);
                mLl3D.setVisibility(View.GONE);
                mLlDynamics.setVisibility(View.GONE);
                mLlSpeed.setVisibility(View.VISIBLE);

                break;
        }

    }

    @Override
    public void onDownClick(String what) {
        Log.e("LongNext", "onDownClick");
        if (CommonUtil.isFastClick()) {
            return;
        } else {
//            BleController.getInst().sendLongclickSingleData(what,true);
        }
    }

    @Override
    public void getTime(String time) {
        sendTime(time);
    }


    public void getPoint(int point) {
        //如果是点击了上
        if (!TextUtils.isEmpty(mActionUpDown) && mActionUpDown.equals("up")) {
            showUpDown();
            mActionUpDown = "";
        } else if (!TextUtils.isEmpty(mActionUpDown) && mActionUpDown.equals("down")) {
            showUpDown();
            mActionUpDown = "";
        }
    }

    private void setUpOrDown() {
        isClickUpOrDown = true;
        mClickUpDownTime = System.currentTimeMillis();
        mHeadup.setEnabled(false);
        mHeadDown.setEnabled(false);
        intervalUpOrDown();
    }

    private void setWidthClick() {
        isClickWidth = true;
        mIvWidthNoClick.setVisibility(View.VISIBLE);
        mClickWidthTime = System.currentTimeMillis();
        mIvLeft.setEnabled(false);
        mIvRight.setEnabled(false);
        intervalWidth();
    }

    public void showUpDown() {
        isClickUpOrDown = false;
        mHeadup.setEnabled(true);
        mHeadDown.setEnabled(true);
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }

    public void showwidth() {
        isClickWidth = false;
        mIvWidthNoClick.setVisibility(View.GONE);
        mIvLeft.setEnabled(true);
        mIvRight.setEnabled(true);
        if (mDisposableWidth != null) {
            mDisposableWidth.dispose();
        }
    }


    /**
     * 单击上下调节3秒还没回复自动变为可点击
     */
    public void intervalUpOrDown() {
        Observable.interval(300, 300, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                        mDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull Long aLong) {
                        if (isClickUpOrDown && System.currentTimeMillis() - mClickUpDownTime > 3000) {
                            showUpDown();

                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        showUpDown();

                    }

                    @Override
                    public void onComplete() {
                    }
                });

    }

    /**
     * 单击宽度调节3秒还没回复自动变为可点击
     */
    public void intervalWidth() {
        Observable.interval(300, 300, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        Log.d("mmmTAG11111", "当前线程：subscribe------" + Thread.currentThread().getName());
                        mDisposableWidth = d;
                    }

                    @Override
                    public void onNext(@NonNull Long aLong) {
                        Log.d("mmmTAG2222", "当前线程：subscribe------" + Thread.currentThread().getName());
                        if (isClickWidth && System.currentTimeMillis() - mClickWidthTime > 3000) {

                            showwidth();

                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        showwidth();
                    }

                    @Override
                    public void onComplete() {
                    }
                });

    }


    private void setTextView(TextView tv, String msg) {
        if (tv != null && msg != null) {
            tv.setText(msg);
        }
    }

    private void updateView() {
        Device7808StateBean device7808StateBean = DataManager.getInst().getDevice7808StateBean();
        getPoint(StringUtils.getValue(device7808StateBean.getYPos()));
        setWidth(StringUtils.getValue(device7808StateBean.getXPos()));
        setArea(StringUtils.getValue(device7808StateBean.getHandProgram()));
        mLayout3D.setShow(StringUtils.getValue(device7808StateBean.get_3DPosIconBean()));
        mLayoutPower.setShow(StringUtils.getValue(device7808StateBean.getMassageStrength()));
        mLayoutSpeed.setShow(StringUtils.getValue(device7808StateBean.getMassageSpeed()));
        //揉捏
        if ("2".equals(device7808StateBean.getKnead())) {
            setSkill(0, 2);
        }
        if ("1".equals(device7808StateBean.getKnead())) {
            setSkill(0, 1);
        } else {
            setSkill(0, 0);
        }
        //敲击
        if ("2".equals(device7808StateBean.getKnock())) {
            setSkill(1, 2);
        }
        if ("1".equals(device7808StateBean.getKnock())) {
            setSkill(1, 1);
        } else {
            setSkill(1, 0);
        }
        //推拿
        if ("1".equals(device7808StateBean.getTuina())) {
            setSkill(2, 1);
        } else {
            setSkill(2, 0);
        }
        //指压
        if ("2".equals(device7808StateBean.getShiasu())) {
            setSkill(3, 2);
        }
        if ("1".equals(device7808StateBean.getShiasu())) {
            setSkill(3, 1);
        } else {
            setSkill(3, 0);
        }
        //拍打
        if ("2".equals(device7808StateBean.getFlap())) {
            setSkill(4, 2);
        }
        if ("1".equals(device7808StateBean.getFlap())) {
            setSkill(4, 1);
        } else {
            setSkill(4, 0);
        }
        //瑞典
        if ("2".equals(device7808StateBean.getSwedish())) {
            setSkill(5, 1);
        } else {
            setSkill(5, 0);
        }
    }

}
